package ynu.edu.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import ynu.edu.dto.RegisterRequest;
import ynu.edu.entity.User;
import ynu.edu.repository.UserRepository;
import ynu.edu.utils.JwtUtil;

@Service
public class UserService {
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    public String login(String username, String password) {
        return userRepository.findByUserName(username)
                .filter(user -> password.equals(user.getPassword()))
                .map(user -> jwtUtil.generateToken(user.getUserName()))
                .orElseThrow(() -> new RuntimeException("用户名或密码错误"));
    }
    
    public void register(RegisterRequest request) {
        if (userRepository.existsByUserName(request.getUserName())) {
            throw new RuntimeException("用户名已存在");
        }
        
        User user = new User();
        user.setUserName(request.getUserName());
        user.setPassword(request.getPassword());
        user.setUserSex(request.getUserSex());
        user.setUserImg("default.jpg");
        user.setDelTag(0);
        
        userRepository.save(user);
    }
    
    public User getUserById(Integer userId) {
        return userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
    }

    public User getUserByName(String userName) {
        return userRepository.findByUserName(userName)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
    }
} 